import { useState, useEffect } from 'react'
import * as echarts from 'echarts'
import { getChartData } from '@/api/home'
import { Card, Tag } from 'antd'

const options = [
  {
    text: '近1个月',
    value: 'month'
  },
  {
    text: '近1周',
    value: 'week'
  },
  {
    text: '近24小时',
    value: 'hour'
  }
]
var myChart: any = null

function EChartItem() {
  const [optionValue, setOptionValue] = useState('week')
  useEffect(() => {
    chartInit()
  }, [])
  useEffect(() => {
    getData()
  }, [optionValue])
  const chartInit = () => {
    var chartDom = document.getElementById('chart')
    if (chartDom) {
      myChart = echarts.init(chartDom)
      getData()
    }
  }
  const getData = () => {
    let option = {
      xAxis: {
        type: 'category',
        data: []
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          data: [],
          type: 'bar',
          showBackground: true,
          backgroundStyle: {
            color: 'rgba(180, 180, 180, 0.2)'
          }
        }
      ]
    }
    myChart.showLoading()
    getChartData(optionValue).then(res => {
      if (res.status === 200) {
        option.xAxis.data = res.data.x
        option.series[0].data = res.data.y
        myChart.setOption(option)
        myChart.hideLoading()
      }
    })
  }
  const tagClick = (value: string) => {
    setOptionValue(value)
  }
  const selectDom = options.map(item => {
    return (
      <Tag.CheckableTag key={item.value} checked={optionValue === item.value} onClick={() => tagClick(item.value)}>
        {item.text}
      </Tag.CheckableTag>
    )
  })
  return (
    <>
      <Card title='订单统计' extra={selectDom}>
        <div id='chart' style={{ width: '100%', height: '300px' }}></div>
      </Card>
    </>
  )
}
export default EChartItem
